package com.tuzhh.htmlrtspplayer.bean;

import com.tuzhh.htmlrtspplayer.service.LocalControlService;
import com.tuzhh.htmlrtspplayer.service.RemoteControlService;
import lombok.Getter;
import lombok.Setter;

import java.util.HashMap;
import java.util.Random;

public class SessionInfo {

    @Getter
    @Setter
    private LocalControlService localControlService = null;
    @Setter
    @Getter
    private RemoteControlService remoteControlService = null;
    @Setter
    @Getter
    private String redirectUrl = null;
    @Setter
    @Getter
    private String url = null;
    @Setter
    @Getter
    private String host = null;
    @Setter
    @Getter
    private int port = 0;

    @Getter
    private String sessionId;
    @Getter
    private String channel;


    private static final HashMap<String, SessionInfo> hsmpSessionInfo = new HashMap<>();
    private static final HashMap<String, SessionInfo> hsmpChannel2SessionInfo = new HashMap<>();
    private static int channelSeq = 0;

    public static SessionInfo getByChannel(String channel) {
        synchronized (hsmpChannel2SessionInfo) {
            return hsmpChannel2SessionInfo.get(channel);
        }
    }

    public static void add(String sessionId, SessionInfo sessionInfo) {
        hsmpSessionInfo.put(sessionId, sessionInfo);
    }

    public static void remove(String sessionId) {
        hsmpSessionInfo.remove(sessionId);
    }

    public static SessionInfo get(String sessionId) {
        return hsmpSessionInfo.get(sessionId);
    }


    public void close() {
        if (localControlService != null) {
            localControlService.close();
        }
        if (remoteControlService != null) {
            remoteControlService.close();
        }
        hsmpChannel2SessionInfo.remove(channel);
    }

    public SessionInfo() {
        sessionId = Integer.toString(channelSeq++);
        Random random = new Random(1000000000);
        channel = Integer.toString(random.nextInt());
        synchronized (hsmpChannel2SessionInfo) {
            hsmpChannel2SessionInfo.put(channel, this);
        }
    }
}
